package com.zxzhu.joyread.Presenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.SignUpCallback;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zxzhu.joyread.Model.LoginModel;
import com.zxzhu.joyread.Model.RegisterModel;
import com.zxzhu.joyread.View.ILoginView;
import com.zxzhu.joyread.View.LoginView;
import com.zxzhu.joyread.View.MainView;
import com.zxzhu.joyread.View.RegisterView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * Created by zia on 17-7-23.
 */

public class LoginPresenter implements ILoginPresenter {

    private ILoginView loginView;
    private LoginModel model;
    private Context context;
    private final static String DEFAULT_PASSWORD = "0";
    private final static String TAG = "LoginPresenterTest";

    public LoginPresenter(LoginView loginView, Context context){
        this.loginView = loginView;
        model = new LoginModel();
        this.context = context;
        PlatformConfig.setQQZone("1106236205", "GhdcgFJu0akTmVjZ");
        PlatformConfig.setSinaWeibo("2203336036", "4ffa7954268162fe2fc6bf519a68ad89","www.baidu.com");
        Config.DEBUG = true;
    }

    @Override
    public void login(final String username, final String password) {
        loginView.showDialog();
        model.login(username, password, new LogInCallback<AVUser>() {
            @Override
            public void done(AVUser avUser, final AVException e) {
                loginView.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loginView.hideDialog();
                        if(e==null){
                            loginView.toast("欢迎回来！");
                            gotoMainView();
                        }else{
                            loginView.toast("账号或密码错误..");
                        }
                    }
                });
            }
        });
    }

    @Override
    public void gotoRegisterView() {
        Intent intent = new Intent(loginView.getActivity(), RegisterView.class);
        loginView.getActivity().startActivity(intent);
    }

    @Override
    public void qqLogin() {
        UMShareAPI.get(loginView.getActivity()).getPlatformInfo(loginView.getActivity(), SHARE_MEDIA.QQ,umListener);
    }

    @Override
    public void wbLogin() {
        UMShareAPI.get(context).getPlatformInfo((Activity) context, SHARE_MEDIA.SINA,umListener );
    }

    @Override
    public void gotoMainView(String nickname,String gender,String iconUrl,String id) {
        Intent intent = new Intent(loginView.getActivity(), MainView.class);
        intent.putExtra("name",nickname);
        intent.putExtra("gender",gender);
        intent.putExtra("iconUrl",iconUrl);
        intent.putExtra("id",id);
        loginView.getActivity().startActivity(intent);
    }

    @Override
    public void gotoMainView() {
        Intent intent = new Intent(loginView.getActivity(), MainView.class);
        loginView.getActivity().startActivity(intent);
    }

    /**
     * 注册并登录
     * @param openId
     * @param nickName
     * @param gender
     * @param iconUrl
     */
    private void registerAndLogin(final String openId, final String nickName, final String gender, final String iconUrl){
        RegisterModel registerModel = new RegisterModel();
        registerModel.registerWithURL(openId, DEFAULT_PASSWORD, nickName,gender, iconUrl, new SignUpCallback() {
            @Override
            public void done(final AVException e) {
                try {
                    AVUser.logIn(openId,DEFAULT_PASSWORD);
                } catch (AVException e1) {
                    e1.printStackTrace();
                }
                loginView.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(e == null){
                            gotoMainView(nickName,gender,iconUrl,openId);
                            Log.d(TAG,"注册成功");
                        }
                        else{
                            loginView.toast("出错啦");
                        }
                    }
                });
            }
        });
    }

    private UMAuthListener umListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            JSONObject userMes = null;
            if (map != null) {
                try {
                    userMes = new JSONObject(map);
                    final String nickName = userMes.getString("name");
                    final String gender = userMes.getString("gender");
                    final String iconUrl = userMes.getString("iconurl");
                    final String openId = userMes.getString("uid");
                    Log.d("openId is",openId);
                    //先查询该qq是否曾登陆过
                    AVQuery<AVUser> query = new AVQuery<>("Fuck");
                    query.whereEqualTo("username",openId);
                    query.findInBackground(new FindCallback<AVUser>() {
                        @Override
                        public void done(List<AVUser> list, AVException e) {
                            if(list.size() == 0)
                            {
                                AVObject user = new AVObject("Fuck");
                                user.put("nickname",nickName);
                                user.put("username",openId);
                                user.put("gender",gender);
                                user.put("password","111");
                                user.saveInBackground(new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        if(e == null)
                                        {
                                            gotoMainView(nickName,gender,iconUrl,openId);
                                        }
                                    }
                                });
                            }
                            else {
                                gotoMainView(nickName,gender,iconUrl,openId);
                            }

                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            loginView.toast("error");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            loginView.toast("cancel");
        }
    };
}
